//
//  FavCuSmerTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/26.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "FavCuSmerTableViewController.h"
#import "ComSumerTableViewCell.h"
#import <MJRefresh.h>
#import "GIFImageArray.h"
#import "Puser.h"
#import "GuzhuType.h"
#import "BottomBar.h"
#import "NoItemView.h"
#import "PersonalDetailViewController.h"
#import "CompanyDetailViewController.h"
@interface FavCuSmerTableViewController ()<UITableViewDataSource,UITableViewDelegate,BottomBarBtnClickDelegate,UIAlertViewDelegate,BottombarDataSource>
{
    BOOL _isedting;
    BOOL _candelete;
}
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) NSMutableArray *datalist;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) BottomBar *bottombar;
@property (nonatomic,weak) NoItemView *notitem;
@end

@implementation FavCuSmerTableViewController
+(instancetype)viewcontroller{
    FavCuSmerTableViewController *favc=[[FavCuSmerTableViewController alloc]init];
    favc.hidesBottomBarWhenPushed=YES;
    return favc;
}

-(BottomBar *)bottombar{
    if (_bottombar==nil) {
        _bottombar=[[BottomBar alloc]initWithBtnTitleArray:@[@"取消关注"] WithDelegate:self :YES];
        _bottombar.ishwopost=NO;
        _bottombar.datasource=self;
        [_bottombar addInView:self.view];
    }
    return _bottombar;
}

-(NSInteger)numberofBottobarcount:(BottomBar *)bottombar{
    return self.datalist.count;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        return;
    }else{
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"取消关注中...";
        
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        params[@"action"]=@"can_sale";
        
        NSMutableArray *IDarray=[NSMutableArray array];
        for (GuzhuType *type in self.datalist) {
            if (type.ischecked) {
                [IDarray addObject:type.ID];
            }
        }
        NSInteger power=[self.user.power integerValue];
        params[@"id"]=[NSString DataTOjsonString:IDarray];
        params[@"user_id"]=power<5?self.user.user_id:self.user.com_id;
        if (power==8) {
            params[@"pid"]=self.user.parent_id;
        }
        params[@"type"]=power<5?@"person":@"company";
        [PostUitls Post:mygzurl parameters:params success:^(id response) {
            
            
            NSDictionary *dict=response;
            NSNumber *state=dict[@"state"];
            if ([state integerValue]==400) {
                _candelete=NO;
                _bottombar.allselected=NO;
                [self.tableView.header beginRefreshing];
            }
            hud.labelText=dict[@"msg"];
            hud.mode=MBProgressHUDModeText;
            [hud hide:YES afterDelay:1];
            
        } failure:^(NSError *error) {
            hud.labelText=NetWorkError;
            hud.mode=MBProgressHUDModeText;
            [hud hide:YES afterDelay:1];
        }];
        
        

    }
}
-(UITableView *)tableView{
    if (_tableView==nil) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, XHScreenwidth, XHScreenheight) style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.backgroundColor=bgGarycolor;
        _tableView.separatorStyle=NO;
        // Uncomment the following line to preserve selection between presentations.
        // self.clearsSelectionOnViewWillAppear = NO;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

-(NSMutableArray *)datalist{
    if (_datalist==nil) {
        _datalist=[NSMutableArray array];
    }
    return _datalist;
}

-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    self.navigationItem.title=@"我的关注";
    
    UINib *comsumer=[UINib nibWithNibName:NSStringFromClass([ComSumerTableViewCell class]) bundle:[NSBundle mainBundle]];
    NoItemView *noitem=[NoItemView viewWithType:STARTTYPE];
    
    [self.tableView addSubview:noitem];
    [self setupRight:NO];
    _notitem=noitem;
    self.tableView.backgroundColor=bgGarycolor;
    [self.tableView registerNib:comsumer forCellReuseIdentifier:@"comsumer"];
    self.tableView.rowHeight=80;
    self.tableView.backgroundColor=bgGarycolor;
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }
    [self setuptablview];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


-(void)rightclick{
    _isedting=!_isedting;
    [self setupRight:_isedting];
    [self.tableView reloadData];
}

-(void)setupRight:(BOOL)iseidting{
    if (iseidting) {
        UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
        [self.bottombar show];
        self.navigationItem.rightBarButtonItem=rightitem;
        
    }else{
        [self.bottombar hide];
        self.bottombar.allselected=NO;
        for (GuzhuType *mode in self.datalist) {
            mode.ischecked=self.bottombar.allselected;
        }
        UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStyleDone target:self action:@selector(rightclick)];
        
        self.navigationItem.rightBarButtonItem=rightitem;
    }
    
    
}
-(void)BottomBarAllclick:(BottomBar *)bottombar{
    for (GuzhuType *mode in self.datalist) {
        mode.ischecked=bottombar.allselected;
    }
    [self.tableView reloadData];
}

-(void)showalert{
    UIAlertView *alret=[[UIAlertView alloc]initWithTitle:@"提示" message:@"确认取消关注么?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alret show];
}

-(void)BottomBar:(BottomBar *)bottombar otherbtnClick:(NSInteger)index{
    if (index==0&&self.datalist.count>0) {
        [self showalert];
    }
    
}




-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GuzhuType *type=self.datalist[indexPath.row];
    if (_isedting) {
        type.ischecked=!type.ischecked;
         ComSumerTableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];
         cell.editbutton.selected=!cell.editbutton.selected;
        for (GuzhuType *type in self.datalist) {
            if (type.ischecked) {
                _candelete=YES;
                break;
            }else{
                _candelete=NO;
            }
        }
        self.bottombar.btnenable=_candelete;
    }else{
        if (![type.user_id isEqualToString:@""]&&type.user_id) {
            PersonalDetailViewController *pvc=[PersonalDetailViewController viewcontroller];
            pvc.user_id=type.user_id;
            [self.navigationController pushViewController:pvc animated:YES];
        }else{
            CompanyDetailViewController *cvc=[CompanyDetailViewController viewcontroller];
            cvc.com_id=type.com_id;
            [self.navigationController pushViewController:cvc animated:YES];
        }
    }
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(void)setuptablview{
    MJRefreshHeader *header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshing)];
    
    
    self.tableView.header=header;
    self.tableView.header.automaticallyChangeAlpha=YES;
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter  footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
   
    footer.stateLabel.font=[UIFont systemFontOfSize:10];
    footer.stateLabel.textColor=RGBACOLOR(125, 125, 125, 1);
    self.tableView.footer=footer;
    self.tableView.footer.automaticallyChangeAlpha = YES;
    
    [self.tableView.header beginRefreshing];
}

-(void)refreshing{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    NSInteger power=[self.user.power integerValue];

    params[@"type"]=power<5?@"person":@"company";
    params[@"num"]=@"8";
    params[@"user_id"]=power<5?self.user.user_id:self.user.com_id;
    params[@"action"]=@"my_fav_sale";
    if (power==8) {
        params[@"pid"]=self.user.parent_id;
    }
    [PostUitls Post:mygzurl parameters:params success:^(id response) {
        NSDictionary *dict=response;
        [self.datalist removeAllObjects];
        
        [GuzhuType setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{
                     @"ID":@"id"
                     };
        }];
        
        NSArray *dataarray=[GuzhuType objectArrayWithKeyValuesArray:dict[@"data"]];
        
        [self.datalist addObjectsFromArray:dataarray];
        if (self.datalist.count>0) {
            [self.notitem hide];
        }else{
            [self.notitem show];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        
    } failure:^(NSError *error) {
        [self.tableView.header endRefreshing];
    }];
    
}
-(void)loadMoreData{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    NSInteger power=[self.user.power integerValue];
    
    params[@"type"]=power<5?@"person":@"company";
    params[@"num"]=@"8";
    params[@"user_id"]=power<5?self.user.user_id:self.user.com_id;
    params[@"action"]=@"my_fav_sale";
    
    NSMutableArray *IDarray=[NSMutableArray array];
    for (GuzhuType *type in self.datalist) {
        [IDarray addObject:type.ID];
    }
    
    params[@"page_id"]=[NSString DataTOjsonString:IDarray];
    
    [PostUitls Post:mygzurl parameters:params success:^(id response) {
        NSDictionary *dict=response;
       ;
        
        [GuzhuType setupReplacedKeyFromPropertyName:^NSDictionary *{
            return @{
                     @"ID":@"id"
                     };
        }];
        
        NSArray *dataarray=[GuzhuType objectArrayWithKeyValuesArray:dict[@"data"]];
        
        [self.datalist addObjectsFromArray:dataarray];
       
        [self.tableView reloadData];
        if (dataarray.count>0) {
            
        }
        [self.tableView.footer endRefreshing];
        
    } failure:^(NSError *error) {
        [self.tableView.footer endRefreshing];
    }];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.datalist.count;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
    
    
}



-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GuzhuType *type=self.datalist[indexPath.row];
    
    
    ComSumerTableViewCell *cell=[ComSumerTableViewCell cellWithTableView:tableView];
    cell.type=type;
    cell.isEidt=_isedting;

    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
